﻿using System;
using System.Web.UI;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using SARS.Biz;
using SARS.Entity;
using SARS.Entity.Factory;

namespace SARS.Course.Group
{
    public partial class GroupEdit : Page
    {
        private GroupEntity group;
        private int groupId;
        private readonly GroupBO groupBiz = new GroupBO();
        private readonly UserBO userBiz = new UserBO();
         
        protected void Page_Load(object sender, EventArgs e)
        {
            
            Response.Cache.SetNoStore();
            if (!string.IsNullOrEmpty(Request.QueryString["gid"]))
            {
                groupId = Int32.Parse(Request.QueryString["gid"]);
                if (!IsPostBack)
                {
                    group = groupBiz.RetrieveGroupById(groupId);
                    group.GroupMembers = userBiz.RetrieveStudentByGroupId(groupId);
                    group.GroupTutorial = userBiz.RetrieveTutorsByGroupId(groupId);

                    hdlabel.Text = group.GroupName;
                    txtGroupName.Text = group.GroupName;
                    lbGroupCourse.Text = group.Course.CourseName;

                    gvGroupTutor.DataSource = group.GroupTutorial;
                    gvGroupTutor.DataBind();
                }
            }
            else
            {
                Response.Redirect("Group.aspx");
            }
        }


        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("Group.aspx");
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            group = GroupFactory.CreateGroup();
            group.GroupName = txtGroupName.Text;
            group.GroupID = groupId;
            groupBiz.UpdateGroup(group);

            var deleteTutors = GetCheckedTutos();

            foreach (string tutorId in deleteTutors)
            {
                groupBiz.RemoveGroupTutor(group.GroupID,Int32.Parse(tutorId));
            }

            Response.Redirect("GroupDetails.aspx?gid="+group.GroupID);
        }

        protected void btnAssignTutor_OnClick(object sender, EventArgs e)
        {
            Response.Redirect("AssignGroupTutor.aspx?gid="+groupId);
        }

        private List<string> GetCheckedTutos()
        {
            var checkedIds = new List<string>();

            foreach (GridViewRow gvrow in gvGroupTutor.Rows)
            {
                string index = gvGroupTutor.DataKeys[gvrow.RowIndex].Value.ToString();
                bool result = ((CheckBox)gvrow.FindControl("cbDelete")).Checked;
                if (result)
                {
                        checkedIds.Add(index);
                }
            }
            return checkedIds;
        }

    }
}